import * as signalR from '@microsoft/signalr'
import $common from '@/utils/open/common'

const baseURL = window.g.WEBAPI_SOCKET_URL // 获取接口地址

const wscUrl = baseURL + 'MessageHub' // process.env.CTX
console.log('signalr - wscUrl: ', wscUrl)
const signal = new signalR.HubConnectionBuilder()
  // 服务器地址
  .withAutomaticReconnect()
  .withUrl(wscUrl, { skipNegotiation: true, transport: signalR.HttpTransportType.WebSockets })
  .configureLogging(signalR.LogLevel.Information)
  .build()

signal.on('ReceiveCaller', function (message) {
  var data = JSON.parse(message)
  // console.log('signal: ', data)
  switch (data.type) {
    case 'init': // 初始化
      console.log('signal-初始化')
      $common.setCookie('client_id', data.client_id)

      signal.invoke('SendMessage', data.client_id, '{"type":"WeChat:AppId"}').catch(function (err) {
        console.log(err.toString())
      })
      break
    case 'login': // 用户登入
      console.log('signal-login')
      break
    case 'logout': // 强退己登入的用户
      // debugger
      console.log('signal-logout')
      break
    default:
      break
  }
})

signal.on('ReceiveMessage', function (message) {
  var joMsg = JSON.parse(message)
  console.log('ReceiveMessage-' + message)
  switch (joMsg.type) {
    case 'WeChat:AppId': // 微信AppId
      $common.setCookie('WeChat:AppId', joMsg.data)
      break
  }
})

signal.on('ConnectResponse', function (message) {
  debugger
  console.log('ConnectResponse-' + message)
})

signal.on('DisconnectResponse', function (message) {
  debugger
  console.log('DisconnectResponse-' + message)
})

signal.start().catch(err => console.log(err.message))

/*
async function OnConnectedAsync() {
  // 发送消息
  signal.invoke('OnConnectedAsync').catch(err => console.error(err.toString()))
  event.preventDefault()
}
*/

//  自动重连
/* async function start () {
  try {
    await signal.start()
    console.log('connected')
  } catch (err) {
    console.log(err)
    setTimeout(() => start(), 5000)
  }
}

signal.onclose(async () => {
  await start()
}) */
// 将创建的signal赋值给Vue实例
export default {
  // install方法的第一个参数是 Vue 构造器，第二个参数是一个可选的选项对象。
  install: function (Vue, options) {
    Vue.prototype.$signalr = signal
  }
}
